# 多轮对话
# https://help.aliyun.com/zh/model-studio/multi-round-conversation

from openai import OpenAI

client = OpenAI(
    api_key = "sk-1341cd7d8e38416ebc0a0e698a622896", #os.getenv("DASHCOPE_API_KEY")
    base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1",
)

def task(messages):
    print("发送问题")

    try:
        completion = client.chat.completions.create(
            model = "qwen-plus",
            messages = messages
        )

        return completion.choices[0].message.content
    except Exception as e:
        print(f"错误信息：{e}")
        print("请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

def main():
    print("多轮对话：")

    messages = []

    # 第 1 轮
    messages.append({"role": "user", "content": "推荐一部关于太空探索的科幻电影。"})
    print("第1轮")
    print(f"用户：{messages[0]['content']}")
    assistant_output = task(messages)
    messages.append({"role": "assistant", "content": assistant_output})
    print(f"模型：{assistant_output}\n")

    # 第 2 轮
    messages.append({"role": "user", "content": "这部电影的导演是谁？"})
    print("第2轮")
    print(f"用户：{messages[-1]['content']}")
    assistant_output = task(messages)
    messages.append({"role": "assistant", "content": assistant_output})
    print(f"模型：{assistant_output}\n")

if __name__ == "__main__":
    main()
